<template>
    <div>
        <div style="margin: 10px 0" v-if="admin">
            <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search"
                      v-model="name"></el-input>
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>
        
        <div style="margin: 10px 0" v-if="admin">
            <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
            <el-popconfirm
                class="ml-5"
                confirm-button-text='确定'
                cancel-button-text='我再想想'
                icon="el-icon-info"
                icon-color="red"
                title="您确定批量删除这些数据吗？"
                @confirm="delBatch"
            >
                <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
            </el-popconfirm>
        </div>
        
        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
            <el-table-column prop="trainNumber" label="车次编号"></el-table-column>
            <el-table-column prop="arrivalTime" label="到达时间" width="140"></el-table-column>
            <el-table-column prop="departureTime" label="发车时间" width="140"></el-table-column>
            <!--      <el-table-column label="图片">-->
            <!--        <template slot-scope="scope">-->
            <!--          <el-image style="width: 100px; height: 100px" :src="scope.row.img"-->
            <!--                    :preview-src-list="[scope.row.img]"></el-image>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <el-table-column prop="startStation" label="起始站"></el-table-column>
            <el-table-column prop="endStation" label="终点站"></el-table-column>
            <el-table-column prop="fee" label="车票价格(元)"></el-table-column>
            <el-table-column prop="ticketType" label="车票类型"></el-table-column>
            <el-table-column label="操作" width="280" align="center">
                <template slot-scope="scope">
                    <el-button v-if="user.role!=='ROLE_ADMIN' && user.role!=='ROLE_TRAIN_ADMIN'" type="success"
                               @click="goupiao(scope.row.id)">购票<i
                        class="el-icon-edit"></i></el-button>
                    <el-button v-if="user.role==='ROLE_ADMIN'  || user.role==='ROLE_TRAIN_ADMIN'" type="success"
                               @click="handleEdit(scope.row)">编辑 <i
                        class="el-icon-edit"></i></el-button>
                    <el-popconfirm v-if="user.role==='ROLE_ADMIN'  || user.role==='ROLE_TRAIN_ADMIN'"
                                   class="ml-5"
                                   confirm-button-text='确定'
                                   cancel-button-text='我再想想'
                                   icon="el-icon-info"
                                   icon-color="red"
                                   title="您确定删除吗？"
                                   @confirm="del(scope.row.id)"
                    >
                        <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        
        <!--编辑或新增表单-->
        <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%">
            <el-form label-width="80px" size="small" status-icon :model="form" :rules="rules" ref="form">
                <el-form-item label="到达时间" prop="arrivalTime">
                    <el-date-picker v-model="form.arrivalTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                                    placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="发车时间" prop="departureTime">
                    <el-date-picker v-model="form.departureTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                                    placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="起始站" prop="startStation">
                    <el-select v-model="form.startStation" filterable placeholder="请选择">
                        <el-option
                            v-for="item in stations"
                            :key="item.stationName"
                            :label="item.stationName"
                            :value="item.stationName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="终点站" prop="endStation">
                    <el-select v-model="form.endStation" filterable placeholder="请选择">
                        <el-option
                            v-for="item in stations"
                            :key="item.stationName"
                            :label="item.stationName"
                            :value="item.stationName">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="车票价格" prop="fee">
                    <el-input v-model="form.fee" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="车票类型" prop="ticketType">
                    <el-select v-model="form.ticketType" placeholder="请选择车票类型">
                        <el-option label="直达" value="直达"></el-option>
                        <el-option label="换乘" value="换乘"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="车次编号" prop="trainNumber">
                    <el-input v-model="form.trainNumber" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </div>
        </el-dialog>
        
        <el-dialog title="购票信息" :visible.sync="ticketDialogVisible" width="60%">
            <!-- 车厢选择下拉组件 -->
            <div style="margin-bottom: 20px;">
                <el-select v-model="selectedCarriage" placeholder="选择车厢" @change="filterTicketsByCarriage">
                    <el-option v-for="carriage in carriages" :key="carriage" :label="`${carriage}车厢`"
                               :value="carriage"></el-option>
                </el-select>
            </div>
            <!-- 车票信息表格 -->
            <el-table :data="filteredTicketData" border stripe>
                <el-table-column prop="carriageNumber" label="车厢号"></el-table-column>
                <el-table-column prop="seatNumber" label="座位号"></el-table-column>
                <el-table-column prop="ticketStatus" label="票务状态">
                    <template slot-scope="scope">
                        <el-tag
                            :type="getTagType(scope.row.ticketStatus)"
                            :closable="false"
                        >
                            {{ getTagLabel(scope.row.ticketStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-popconfirm
                            v-if="scope.row.ticketStatus === '未售出' "
                            title="确定购买这张车票吗？"
                            @confirm="purchaseTicket(scope.row)"
                        >
                            <el-button slot="reference" type="primary">购买</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>

export default {
    name: "TbTrain",
    data() {
        return {
            tableData: [],
            total: 0,
            pageNum: 1,
            pageSize: 10,
            name: "", carriages: [1, 2, 3, 4, 5], // 车厢号范围
            form: {},
            dialogFormVisible: false, filteredTicketData: [], // 筛选后的车票数据
            ticketDialogVisible: false, selectedCarriage: '', // 选中的车厢号
            multipleSelection: [],
            user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
            ticketData: [],
            stations: [],
            admin:false,
            rules: {
                arrivalTime: [
                    {required: true, message: '请选择发车时间', trigger: 'blur'},
                ],
                trainNumber: [
                    {required: true, message: '请输入车次编号', trigger: 'blur'},
                ],
                startStation: [
                    {required: true, message: '请选择起始站', trigger: 'blur'},
                ],
                endStation: [
                    {required: true, message: '请选择终点站', trigger: 'blur'},
                ],
                departureTime: [
                    {required: true, message: '请选择发车时间', trigger: 'blur'},
                ],
                fee: [
                    {required: true, message: '请输入车票价格', trigger: 'blur'},
                ],
                ticketType: [
                    {required: true, message: '请选择车票类型', trigger: 'blur'},
                ],
            }
        }
    },
    created() {
        this.admin = this.user.role.includes("ADMIN");
        this.load();
        this.getStations();
    },
    methods: {
        getStations() {
            this.request.get("/tbStation").then(res => {
                this.stations = res.data
            })
        },
        getTagType(status) {
            switch (status) {
                case '售票':
                    return 'success'; // 或根据需要选择其他类型
                case '改签':
                    return 'warning';
                case '退票':
                    return 'warning'; // 将退票颜色改为黄色
                case '未售出':
                    return 'info';
                default:
                    return 'default';
            }
        },
        getTagLabel(status) {
            if (status === '售票') {
                return '已售出';
            } else if (status === '退票') {
                return '退票中'; // 将退票显示改为退票中
            }
            return status;
        },
        filterTicketsByCarriage() {
            if (this.selectedCarriage) {
                this.filteredTicketData = this.ticketData.filter(ticket => ticket.carriageNumber == this.selectedCarriage);
            } else {
                this.filteredTicketData = this.ticketData;
            }
        },
        goupiao(row) {
            this.ticketDialogVisible = true
            this.request.get("/tbTicket/page", {
                params: {
                    pageNum: 1,
                    pageSize: 1000,
                    name: row
                }
            }).then(res => {
                this.ticketData = res.data.records
            })
        },
        load() {
            this.request.get("/tbTrain/page", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    name: this.name,
                }
            }).then(res => {
                this.tableData = res.data.records
                this.total = res.data.total
            })
        },
        save(formName) {
            if(this.form.startStation === this.form.endStation){
                this.$message.error("起始站和终点站不能相同");
                return;
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.request.post("/tbTrain", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message.success("保存成功")
                            this.dialogFormVisible = false
                            this.load()
                        } else {
                            this.$message.error("保存失败")
                        }
                    })
                } else {
                    this.$message.error("请按要求输入")
                    return false;
                }
            });
        },
        handleAdd() {
            this.dialogFormVisible = true
            this.form = {}
            this.$nextTick(() => {
                if (this.$refs.img) {
                    this.$refs.img.clearFiles();
                }
                if (this.$refs.file) {
                    this.$refs.file.clearFiles();
                }
            })
        },
        del(id) {
            this.request.delete("/tbTrain/" + id).then(res => {
                if (res.code === '200') {
                    this.$message.success("删除成功")
                    this.load()
                } else {
                    this.$message.error("删除失败")
                }
            })
        },
        delBatch() {
            if (!this.multipleSelection.length) {
                this.$message.error("请选择要删除的数据")
                return
            }
            let ids = this.multipleSelection.map(item => item.id)
            console.log('ids:',ids)
            this.request.post("/tbTrain/del/batch",ids).then(res => {
                if (res.code === '200') {
                    this.$message.success("删除成功")
                    this.load()
                } else {
                    this.$message.error("删除失败")
                }
            })
        },
        handleEdit(row) {
            this.dialogFormVisible = true
            this.form = {...row}
            this.$nextTick(() => {
                if (this.$refs.img) {
                    this.$refs.img.clearFiles();
                }
                if (this.$refs.file) {
                    this.$refs.file.clearFiles();
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        handleCurrentChange(page) {
            this.pageNum = page
            this.load()
        },
        handleSizeChange(size) {
            this.pageSize = size
            this.load()
        },
        reset() {
            this.name = ""
            this.load()
        },
        exp() {
            window.location.href = "http://localhost:9090/tbTrain/export"
        },
        handleExcelImportSuccess() {
            this.$message.success("导入成功")
            this.load()
        },
        handleImgUploadSuccess(response) {
            console.log(response)
            this.form.img = response
        },
        purchaseTicket(ticket) {
            ticket.ticketStatus = "售票";
            this.request.post("/tbTicket?userId=" + this.user.id + "&nickname=" + this.user.nickname, ticket).then(res => {
                if (res.code === '200') {
                    this.$message.success("购票成功")
                    this.ticketDialogVisible = false
                    
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000); // 延迟时间 1000 毫秒，即 1 秒钟
                    // this.load()
                    // this.goupiao(ticket.trainId)
                } else {
                    this.$message.error("保存失败")
                }
            })
        }
    }
}
</script>
